from datetime import datetime, timedelta

from jwt import encode, InvalidTokenError, ExpiredSignatureError, DecodeError, decode

salt = 'iv%x1fo9l7_u9bf_u!9#g#m*)*=ej@bek5)(@u3kh*72+unjv='


def generate_token(play_load: dict, minutes: int):
    """
    生成token
    :param minutes: 多久过期，单位：分钟
    :param play_load: 一般为用户id、用户名的字典
    :return:
    """
    # 构造header
    headers = {
        'type': 'jwt',
        'alg': 'HS256'
    }
    # token有效期，我这边设置为了分钟，即x分钟后过期
    play_load['exp'] = datetime.utcnow() + timedelta(minutes=minutes)
    # 构造signature即token
    token = encode(payload=play_load, key=salt, algorithm="HS256", headers=headers)
    return token


def validate_token(token):
    """
    校验token有效性
    :param token:加密token
    :return: 状态
    """

    # 定义返回相应字典
    result = {'status': False, 'data': None, 'error': None}
    try:
        verified_payload = decode(token, salt, algorithm='HS256', options={"verify_signature": False})
        result['status'] = True
        result['data'] = verified_payload
    except ExpiredSignatureError:
        result['error'] = 'token已失效'
    except DecodeError:
        result['error'] = 'token认证失败'
    except InvalidTokenError:
        result['error'] = '非法的token'
    return result


if __name__ == '__main__':
    print(generate_token({"id": 1}, 10))
    print(validate_token(
        'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsInR5cGUiOiJqd3QifQ.eyJpZCI6MSwiZXhwIjoxNjg5NDI2MDM0fQ'
        '.TZKt9EDijCeGsu5UD3868XnHZY2yuN_K5BWjeDz6QXk'))
